<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * Amazon ECS Child Class
 */
class Model_Amazon extends Model_AmazonAbstract
{

    /**
     * searching
     * @return array|object return type depends on setting
     *
     * @see returnType()
     */
    public function search($pattern, $nodeId = null, $page=1,$additinal=array())
    {
        if (false === isset($this->requestConfig['category']))
        {
            $this->requestConfig['category'] = 'Electronics';
        }

        $browseNode = array();
        if (null !== $nodeId && true === $this->validateNodeId($nodeId))
        {
            $browseNode = array('BrowseNode' => $nodeId);
        }
        $par = array(
            'Keywords'    => $pattern,
            'SearchIndex' => $this->requestConfig['category'],
            'ItemPage'    => $page,
        );
        if (isset($additinal['Manufacturer']))
        {
            $par['Manufacturer'] = $additinal['Manufacturer'];
        }
        if (isset($additinal['MaximumPrice']) && $_POST['MaxPrice'] != '')
        {
            $par['MaximumPrice'] = $additinal['MaximumPrice'];
        }
        if (isset($additinal['MinimumPrice']))
        {
            $par['MinimumPrice'] = $additinal['MinimumPrice'];
        }
        if (isset($additinal['Title']))
        {
            $par['Title'] = $additinal['Title'];
        }

        $par['Condition'] = 'All';

        $params = $this->buildRequestParams(
            'ItemSearch', array_merge(
                $par, $browseNode
            )
        );

        return $this->returnData(
            $this->performSoapRequest("ItemSearch", $params)
        );
    }
 
    public function createCart($asin, $quantity)
    {
        $par=array();
        $par['Items']['Item']['OfferListingId']=$asin;
        $par['Items']['Item']['Quantity'] = $quantity;
        $par['OfferListingId']=$asin;
        
        $params = $this->buildRequestParams('CartCreate', $par);
        
        return $this->returnData(
                $this->performSoapRequest("CartCreate", $params) );
    
    } 
    public function multipleCreateCart($items)
    {
       
        $param=array();
        for ($i = 0; $i < count($items); $i++) 
        {
            $params['Items']['Item'][$i]['OfferListingId']=$items[$i]['asin'];
           // echo "GGGGGGGGGGG".$items[$i]['asin'];
            $params['Items']['Item'][$i]['Quantity']="1";
            
        }
        $params = $this->buildRequestParams('CartCreate',$param);
        return $this->returnData(
                $this->performSoapRequest("CartCreate", $params) );
    
    }     
 
    public function cartAdd($offerListingId, $cartId, $hmac, $quantity )
    {
        $par=array();
        $par['Items']['Item']['OfferListingId']=$offerListingId;
        $par['Items']['Item']['Quantity'] = $quantity;
        $par['OfferListingId']=$offerListingId;
        $par['CartId']=$cartId;
        $par['HMAC']=$hmac;
        
        $params = $this->buildRequestParams('CartCreate', $par);
        return $this->returnData(
                $this->performSoapRequest("CartAdd", $params) );
        
    }
    
    public function cartDelItem($offerListingId, $cartId, $hmac, $cartItemID )
    {
        $par=array();
        $par['Items']['Item']['OfferListingId']=$offerListingId;
        $par['Items']['Item']['Quantity'] = 0;
        $par['Items']['Item']['CartItemId']=$cartItemID;
        //$par['OfferListingId']=$offerListingId;
        $par['CartId']=$cartId;
        $par['HMAC']=$hmac;
        $params = $this->buildRequestParams('CartModify', $par);
        return $this->returnData(
                $this->performSoapRequest("CartModify", $params) );
        
    }
    
    public function cartClear($cartId, $hmac)
    {
        $params = $this->buildRequestParams('CartClear',array(
            'CartId'=> $cartId,
            'HMAC'=> $hmac
            ));
        return $this->returnData(
                $this->performSoapRequest("CartClear", $params) );
       
    }
    
    public function cartGet($cartId, $hmac)
    {
        $params=  $this->buildRequestParams('CartGet', array(
            'CartId'=> $cartId,
            'HMAC'=> $hmac          
        ));
        return $this->returnData(
                $this->performSoapRequest("CartGet", $params) );
    }

    /**
     * @param string $function Name of the function which should be called
     * @param array $params Requestparameters 'ParameterName' => 'ParameterValue'
     *
     * @return array The response as an array with stdClass objects
     */
    protected function performSoapRequest($function, $params)
    {
        if (true === $this->requestConfig['requestDelay'])        
            sleep(1);
        $soapClient = new SoapClient(
                $this->webserviceWsdl, array('exceptions' => 1));

        $soapClient->__setLocation(str_replace('%%COUNTRY%%', 
                $this->responseConfig['country'], $this->webserviceEndpoint));

        $soapClient->__setSoapHeaders($this->buildSoapHeader($function));

        try
        {
            $response = $soapClient->__soapCall($function, array($params));
        }  
        catch (Exception $err)
        {
            // Произошла ошибка запроса к 
            if(count($_POST))
            {
                die('Error 503 (Service Temporarily Unavailable)');
            }
            else
            {
                sleep(2);
                header('Location: ' . $_SERVER['REQUEST_URI']);
                exit;
            }
        }

        return $response;
    }

}